package it.polito.connectedcar.tcc.network;

import it.polito.connectedcar.message.TCCFromTrafficLightMessage;
import it.polito.connectedcar.tcc.tl.TCCTrafficLightsManager;

import java.util.concurrent.BlockingQueue;

/**
 * This Loop is used to analyze messages coming from the TrafficLights and
 * possibly update underlying memory structures to reflect changes such as the
 * phase index of a given traffic light and so on. It uses a common queue used
 * also by lower levels by inserting messages just received from the network.
 * Here the queue is used to read such messages and to invoke a
 * {@link TCCTrafficLightsManager} update methods to update information
 * 
 * @author Nicola Aresta
 * 
 */
public class TCCTrafficLightsMessageQueueMainLoop extends Thread {

	private BlockingQueue<TCCFromTrafficLightMessage> trafficLightReadMessageQueue;
	private TCCTrafficLightsManager trafficLightsManager;

	public TCCTrafficLightsMessageQueueMainLoop(
			TCCTrafficLightsManager trafficLightsManager,
			BlockingQueue<TCCFromTrafficLightMessage> tlMessagesQueue)
			throws Exception {
		this.trafficLightReadMessageQueue = tlMessagesQueue;
		this.trafficLightsManager = trafficLightsManager;
	}

	@Override
	public void run() {
		super.run();

		while (true) {
			try {
				TCCFromTrafficLightMessage message = trafficLightReadMessageQueue
						.take();
				if (message.processMessage(null))
					trafficLightsManager.updateTrafficLight(
							message.getTrafficLightId(),
							message.getCurrentPhaseIndex(),
							message.getLastChangeTimestamp(),
							message.getAssumedTimeToNextPhaseSwitch());

			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
